//
//  NetWorking.m
//  pacc
//
//  Created by 测试 on 2018/5/17.
//  Copyright © 2018年 测试. All rights reserved.
//

#import "NetWorking.h"
#import <SVProgressHUD.h>
#import "loginViewController.h"
@implementation NetWorking

//POST请求   url为传入的网址， parameters为请求的参数以字典形式传入
+ (void)startPOSTRequestWithUrl:(NSString *)url parameters:(NSDictionary *)parameters logMes:(NSString *)logMes show:(BOOL)isShow success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"zzapi" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *temStr =  [NSString stringWithFormat:@"%@%@",[data objectForKey:@"baseURL"],[data objectForKey:url]];
    NSURL *URL = [NSURL URLWithString:temStr];
    NSLog(@"%@URL=%@",logMes,temStr);
    // 将参数添加在请求体中
    NSMutableString * str = [NSMutableString string];
    //参数处理
    if (parameters) {
        
        for (NSString * key in parameters) {
            
            [str appendFormat:@"%@=%@&", key, parameters[key]];
        }
    }
    
    // 创建请求体
    NSData * body = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    // 创建URL
    
    // 创建可变请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    
    // 设置请求方法
    [request setHTTPMethod:@"POST"];
    
    request.timeoutInterval = 1000;
    
    // 设置请求体
    [request setHTTPBody:body];
    
    // 实例化网络会话.
    NSURLSession *session = [NSURLSession sharedSession];
    [SVProgressHUD show];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //全局队列+异步任务
        dispatch_async(queue, ^{
            // 根据请求对象创建请求任务
            NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                [SVProgressHUD dismiss];
                if (data) {
                    //回调代理方法，并传入请求结果
                    if (error) {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                        });
                        failureBlock(error);
                    } else {
                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"%@nresponse=%@",logMes,response);
                            if (!dic) {
                                [SVProgressHUD showErrorWithStatus:@"连接失败"];
                                [my_AppDelegate.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
                                loginViewController *loginVc = [[loginViewController alloc] init];
                                my_AppDelegate.window.rootViewController = loginVc;
                                return ;
                            }
                            NSString *status = [NSString stringWithFormat:@"%@",[dic objectForKey:@"status"]];
                            if ([status isEqualToString:@"200"]) {
                                if (isShow) {
                                    NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                                    [SVProgressHUD showSuccessWithStatus:msg];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [SVProgressHUD dismiss];
                                    });
                                }
                                
                            }else if ([status isEqualToString:@"403"]){
                                NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                                [SVProgressHUD showErrorWithStatus:msg];
                                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
                                [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                                [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    //                                        [SVProgressHUD dismiss];
                                });
                                return;
                            }else{
                                [my_AppDelegate.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
                                loginViewController *loginVc = [[loginViewController alloc] init];
                                my_AppDelegate.window.rootViewController = loginVc;
                                return;
                            }
                    
                            NSData* json = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
                            NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
                            if ([dic isEqual:[NSNull null]]) {
                                [SVProgressHUD showErrorWithStatus:@"连接失败"];
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    [SVProgressHUD dismiss];
                                });
                                return ;
                            }else{
                                successBlock(dic);
                            }
                            NSLog(@"%@参数=%@\nresponse=%@\n%@返回结果=%@",logMes,parameters,response,logMes,dic);
                           
                        });
                    }
                    
                }else {
                    
                    
                }
            }];
            
            // 开启任务. 
            [task resume];
        });
}
//进入登录页面
- (void)setupLoginViewController
{
   
}
+ (void)startPOSTRequestWithUrl2:(NSString *)url parameters:(NSDictionary *)parameters logMes:(NSString *)logMes success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"zzapi" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *temStr =  [NSString stringWithFormat:@"%@%@",[data objectForKey:@"baseURL"],[data objectForKey:url]];
    NSURL *URL = [NSURL URLWithString:temStr];
    NSLog(@"%@URL=%@",logMes,temStr);
    
    // 将参数添加在请求体中
    NSMutableString * str = [NSMutableString string];
    //参数处理
    if (parameters) {
        
        for (NSString * key in parameters) {
            
            [str appendFormat:@"%@=%@&", key, parameters[key]];
        }
    }
    
    // 创建请求体
    NSData * body = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    // 创建URL
    
    // 创建可变请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    
    // 设置请求方法
    [request setHTTPMethod:@"POST"];
    
    request.timeoutInterval = 1000;
    
    // 设置请求体
    [request setHTTPBody:body];
    
    // 实例化网络会话.
    NSURLSession *session = [NSURLSession sharedSession];
    NSLog(@"-=-=-=-=-=-=-=-=-=%@parameters=%@--==-=-=-=--=-",logMes,parameters);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //全局队列+异步任务
    dispatch_async(queue, ^{
        // 根据请求对象创建请求任务
        NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%@parameters=%@,response=%@",logMes,parameters,response);
            if (data) {
                //回调代理方法，并传入请求结果
                if (error) {
                    failureBlock(error);
                } else {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSLog(@"%@==%@",logMes,dic);
                    NSString *status = [NSString stringWithFormat:@"%@",[dic objectForKey:@"status"]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        successBlock(dic);
                        if ([status isEqualToString:@"200"]) {
                            NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                            [SVProgressHUD showSuccessWithStatus:msg];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [SVProgressHUD dismiss];
                            });
                            
                        }else{
                            NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                            [SVProgressHUD showErrorWithStatus:msg];
                            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
                            [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                            [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                                [SVProgressHUD dismiss];
                            });
                        }
                    });
                }
                
            }else {
                
                
            }
        }];
        
        // 开启任务.  //这一步很关键，如果没有这一步，请求任务不会执行
        [task resume];
    });
}
- (void)postJsonToServer:(NSString*)url dic:(NSMutableDictionary*)bodyDic {
    
    NSDictionary *body = @{@"UI_NAME":@"FSEAFNSEFN"};
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bodyDic options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"Reply JSON: %@", responseObject);
            
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                //blah blah
                
            }
            
        } else {
            
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    
}


- (void)startPOSTRequestWithUrl2:(NSString *)url parameters:(NSDictionary *)parameters logMes:(NSString *)logMes success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{
    
    // 将参数添加在请求体中
    NSMutableString * str = [NSMutableString string];
    //参数处理
    if (parameters) {
        
        for (NSString * key in parameters) {
            
            [str appendFormat:@"%@=%@&", key, parameters[key]];
        }
    }
    
    // 创建请求体
    NSData * body = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    // 创建URL
    NSURL * URL = [NSURL URLWithString:url];
    
    // 创建可变请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    
    // 设置请求方法
    [request setHTTPMethod:@"POST"];
    
    request.timeoutInterval = 10;
    
    // 设置请求体
    [request setHTTPBody:body];
    
    // 实例化网络会话.
    NSURLSession *session = [NSURLSession sharedSession];
    [SVProgressHUD show];
    
    // 根据请求对象创建请求任务
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (data) {
            
            //回调代理方法，并传入请求结果
            if (error) {
                failureBlock(error);
            } else {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"%@==%@",logMes,dic);
                successBlock(dic);
            }
            
        }else {
            
            
        }
    }];
    
    // 开启任务.  //这一步很关键，如果没有这一步，请求任务不会执行
    [task resume];
}

//GET请求  url为传入的网址， parameters为请求的参数以字典形式传入
- (void)startGETRequestWithUrl:(NSString *)url parameters:(NSDictionary *)parameters {
    
    //GET请求需要将参数拼接在url后面
    //网络接口和参数 以“?”分隔. 参数和参数之间以“&”符号分隔。
    // 拼接url及参数
    NSMutableString * str = [NSMutableString string];
    
    [str appendString:url];
    
    //当有参数时将参数拼接上去（
    if (parameters.count > 0) {
        
        //以"?"结尾做了判断，有的话就不需要再拼接"?"
        if (![str hasSuffix:@"?"]) {
            
            [str appendString:@"?"];
        }
        
        //拼接参数
        for (NSString * key in parameters) {
            
            [str appendFormat:@"%@=%@&", key, parameters[key]];
        }
        
        //注意最后一个"&"符号需要去掉
        [str deleteCharactersInRange:NSMakeRange(str.length - 1, 1)];
    }
    
    // 设置URL
    NSURL * URL = [NSURL URLWithString:str];
    
    // 实例化网络会话.
    NSURLSession * session = [NSURLSession sharedSession];
    
    //根据URL创建请求任务
    NSURLSessionDataTask * task = [session dataTaskWithURL:URL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (!error) {
            
            //请求成功  对请求的数据做初步的json解析
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //回调代理方法，并传入请求结果
            if ([self.delegate respondsToSelector:@selector(requestDidSuccessData:)]) {
                
                [self.delegate requestDidSuccessData:object];
            }
        }else {
            
            //请求失败  回调代理方法，并传入错误信息
            if ([self.delegate respondsToSelector:@selector(requestDidFailedError:)]) {
                
                [self.delegate requestDidFailedError:error];
            }
        }
    }];
    
    // 开启任务.
    [task resume];
}
//把NSDictionary解析成post格式的NSString字符串
+ (NSString *)parseParams:(NSDictionary *)params
{
    NSString *keyValueFormat;
    NSMutableString *result = [NSMutableString new];
    NSMutableArray *array = [NSMutableArray new];
    //实例化一个key枚举器用来存放dictionary的key
    NSEnumerator *keyEnum = [params keyEnumerator];
    id key;
    while (key = [keyEnum nextObject]) {
        keyValueFormat = [NSString stringWithFormat:@"%@=%@&", key, [params valueForKey:key]];
        [result appendString:keyValueFormat];
        [array addObject:keyValueFormat];
    }
    return result;
}
//验证码

+(void)getCode:(NSString *)PhoneStr btn:(UIButton*)huoquyanzhengmaBtn{
    if (PhoneStr.length != 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
   
    [self startPOSTRequestWithUrl:[NSString stringWithFormat:@"usersendSms"] parameters:@{@"phone":PhoneStr} logMes:@"获取验证码" show:YES success:^(NSDictionary *data) {
        __block NSInteger time = 59; //倒计时时间
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        
        dispatch_source_set_event_handler(_timer, ^{
            
            if(time <= 0){ //倒计时结束，关闭
                
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置按钮的样式
                    [huoquyanzhengmaBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                    [huoquyanzhengmaBtn setTitleColor:RGB(60, 129, 240) forState:UIControlStateNormal];
                    huoquyanzhengmaBtn.userInteractionEnabled = YES;
                });
                
            }else{
                
                int seconds = time % 60;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置按钮显示读秒效果
                    [huoquyanzhengmaBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                    [huoquyanzhengmaBtn setTitleColor:RGB(136, 136, 136) forState:UIControlStateNormal];
                    huoquyanzhengmaBtn.userInteractionEnabled = NO;
                });
                time--;
            }
        });
        dispatch_resume(_timer);
    } failure:^(NSError *error) {
    
    }];

// 开启倒计时效果

    
    
}

//上传
+ (void)upDateHeadIcon:(UIImage *)photo parameters:(NSMutableDictionary*)parameters imageName:(NSString*)imageName success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock
{
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"zzapi" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSString *temStr =  [NSString stringWithFormat:@"%@",[data objectForKey:@"baseURL"]];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/user/putFile?token=%@",temStr,my_AppDelegate.token];
    
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.上传文件
//    NSDictionary *dict = @{@"username":@"1234"};
    
    [manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传文件参数
        NSData *data = UIImagePNGRepresentation(photo);
        //这个就是参数
        [formData appendPartWithFileData:data name:@"file" fileName:[NSString stringWithFormat:@"%@.png",imageName] mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        [SVProgressHUD showWithStatus:@"上传中"];
        //打印下上传进度
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
        //请求成功
        NSLog(@"请求成功：%@",responseObject);
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败
        NSLog(@"请求失败：%@",error);
        failureBlock(error);
    }];
    
}


@end
